package ae.pcfc.cldos.online.web.controller.admin.general.finance.services;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.util.WebUtils;

import ae.pcfc.cldos.online.common.delegate.FnpGSDelegate;
import ae.pcfc.cldos.online.common.vo.FnpDefaultParamsVO;
import ae.pcfc.cldos.online.common.vo.FnpParamMapperVO;
import ae.pcfc.cldos.online.fnp.ConstantsFNP;
import ae.pcfc.cldos.online.fnp.service.client.vo.FNPCatalogVO;
import ae.pcfc.cldos.online.fnp.service.client.vo.FNPParameterVO;
import ae.pcfc.cldos.online.web.Constants;
import ae.pcfc.cldos.online.web.ViewPath;
import ae.pcfc.cldos.online.web.controller.base.BaseController;
import ae.pcfc.cldos.online.web.model.FinanceServicesInfo;

@Controller
@RequestMapping(value = ViewPath.__ADMIN_FINANCE_SERVICES)
public class FinanceServicesController extends BaseController {

	private FnpGSDelegate FnpGSDelegate;
	@Resource(name = "FnpGSDelegate")
	public void setFnpGSDelegate(FnpGSDelegate FnpGSDelegate) {
		this.FnpGSDelegate = FnpGSDelegate;
	}
	
	private static List<FNPCatalogVO> catalogs = new ArrayList<FNPCatalogVO>();
	private static List<FNPCatalogVO> allCatalogs = new ArrayList<FNPCatalogVO>();
	private static List<FNPParameterVO> fnpparameterList = new ArrayList<FNPParameterVO>();
	
	
	//ASNA!!! It will not work correct. Dont use global variables
	String displayParameter = "NO";
	
	/**
	 * @param model
	 */
	@ModelAttribute
	public void populateBreadCrumbs(ModelMap model) {
		breadCrumbsFactoryService.populateFinServicesBreadCrumb(model);
	}
	
	/**
	 * 
	 */
	@RequestMapping(value = "/show.htm", method = RequestMethod.GET)
	public void show() {
		catalogs = new ArrayList<FNPCatalogVO>();
		allCatalogs = FnpGSDelegate.retreiveFNPCatalog(null);
	}
	/**
	 * @param request
	 * @return
	 */
	@ModelAttribute("catalogList")
	public List<FNPCatalogVO> getCatalogList(HttpServletRequest request){
		if(allCatalogs==null || allCatalogs.size()==0){
			 allCatalogs = FnpGSDelegate.retreiveFNPCatalog(null);
		}
		return allCatalogs;
	}
	
	/**
	 * @param request
	 * @return
	 */
	/*@ModelAttribute("selectedCatalogList")
	public List<FNPCatalogVO> getSelectedCatalogList(HttpServletRequest request){
		return this.catalogs;
	}*/
	/**
	 * @param request
	 * @param status
	 * @param financeServicesInfo
	 * @param errors
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/show.htm")
	public FinanceServicesInfo show(
			HttpServletRequest request,
			SessionStatus status,
			@ModelAttribute(value = Constants.__ADMIN_FINANCE_SERVICES_INFO_REQUEST_MODEL_KEY) @Valid FinanceServicesInfo financeServicesInfo,
			BindingResult errors) throws Exception {
		
		boolean isSubmitAdd = WebUtils.hasSubmitParameter(request, "AddButton");
		boolean isSubmitRemove = WebUtils.hasSubmitParameter(request, "RemoveButton");
		boolean isSubmitConfirm = WebUtils.hasSubmitParameter(request, "ConfirmButton");
		boolean isSubmitSave =WebUtils.hasSubmitParameter(request, "SaveButton");
		if(WebUtils.hasSubmitParameter(request, "SaveButton1")){
			 isSubmitSave = WebUtils.hasSubmitParameter(request, "SaveButton1");
		}
		String stepCode = financeServicesInfo.getStepCode();
		if((stepCode==null || stepCode.isEmpty())){
			catalogs=new ArrayList<FNPCatalogVO>();
			errors.reject("label.finserv.stepCode");
			displayParameter=ConstantsFNP.FNP_NO;
		}else{
			
			List<FNPCatalogVO> selectedCatalogs = financeServicesInfo.getSelectedCatalogs();
			if(isSubmitAdd){
				String addCode = financeServicesInfo.getFnpAddCatalogCode();
				if((addCode==null || addCode.isEmpty())){
					errors.reject("label.finserv.addcode");
				}else{
					if(selectedCatalogs==null){
						selectedCatalogs = new ArrayList<FNPCatalogVO>();
					}
					System.out.println("sdfsd");
					for(FNPCatalogVO fnpCatalogVO : allCatalogs){
						if(addCode!=null && !addCode.equals(ConstantsFNP.FNP_NO_VALUE) && fnpCatalogVO.getCode().equals(addCode)){
							catalogs.add(fnpCatalogVO);
							break;
						}
					}
					displayParameter=ConstantsFNP.FNP_NO;
				}
			}else if(isSubmitRemove){
				String removeCode = financeServicesInfo.getFnpRemoveCatalogCode();
				if((removeCode==null || removeCode.isEmpty())){
					errors.reject("label.finserv.removecode");
				}else{
					for(FNPCatalogVO fnpCatalogVO :catalogs){
						if(removeCode!= null && !removeCode.equals(ConstantsFNP.FNP_NO_VALUE) && fnpCatalogVO.getCode().equals(removeCode)){
							catalogs.remove(fnpCatalogVO);
							break;
						}
					}
					displayParameter=ConstantsFNP.FNP_NO;
				}
			}
			//parameter
			else if(isSubmitSave && catalogs!=null && catalogs.size()!=0 ){
				boolean flag=true;
				displayParameter=ConstantsFNP.FNP_NO;
				String serviceCode = financeServicesInfo.getStepCode();
				//items for saving
				String paramName = financeServicesInfo.getParamName();
				String[] paramNameArray = new String[50];
				if(paramName!=null && paramName!=ConstantsFNP.FNP_NO_VALUE){
					if(paramName.contains(ConstantsFNP.FNP_DELIMITER)){
						paramNameArray  = paramName.split(ConstantsFNP.FNP_DELIMITER);
					}else{
						paramNameArray[0]=paramName;
					}
					
				}
				//mapping
				String[] mappingArray = new String[50];
				String mapping = financeServicesInfo.getMapping();
				if(mapping!=null && mapping!=ConstantsFNP.FNP_NO_VALUE){
					if(mapping.contains(ConstantsFNP.FNP_DELIMITER)){
						mappingArray  = mapping.split(ConstantsFNP.FNP_DELIMITER);
					}else{
						mappingArray[0]=mapping;
					}
					
				}
				//static value
				String[] staticValueArray = new String[50];
				String staticValue = financeServicesInfo.getStaticValue();
				if(staticValue!=null && staticValue!=ConstantsFNP.FNP_NO_VALUE){
					if(staticValue.contains(ConstantsFNP.FNP_DELIMITER)){
						staticValueArray  = staticValue.split(ConstantsFNP.FNP_DELIMITER);
					}else{
						staticValueArray[0]=staticValue;
					}
					for(int count=0; count<staticValueArray.length; count++){
						String val = staticValueArray[count];
						if(val!=null && val.length()>10){
							errors.reject("label.finserv.staticSize");
							flag=false;
							break;
						}
					}
				}
				if(flag){
					int i=0;
					int j=0;
					List<FnpParamMapperVO> fnpParamMapperVOs = new ArrayList<FnpParamMapperVO>();
					List<String> serviceIdList = new ArrayList<String>();
					if(fnpparameterList!=null && fnpparameterList.size()!=0){
						for(FNPParameterVO fnpParameterVO :fnpparameterList){
							FnpParamMapperVO fnpParamMapperVO = new FnpParamMapperVO();
							fnpParamMapperVO.setFpmMapping(mappingArray[i]);
							if(mappingArray[i].equals(ConstantsFNP.FNP_STATIC)){
								fnpParamMapperVO.setFpmType(staticValueArray[j]);
								j++;
							}
							for(FNPParameterVO fnpParametVo :fnpparameterList){
								if(fnpParametVo.getName().equals(paramNameArray[i])){
									fnpParamMapperVO.setFpmParamName(paramNameArray[i]);
									fnpParamMapperVO.setFpmServiceId(fnpParametVo.getServiceId());
									break;
								}
							}
							fnpParamMapperVOs.add(fnpParamMapperVO);
							serviceIdList.add(fnpParameterVO.getServiceId());
							i++;
						}
						FnpGSDelegate.saveParamMapping(fnpParamMapperVOs,serviceIdList);
					}
					FnpGSDelegate.insertAll(catalogs, serviceCode);
					catalogs=new ArrayList<FNPCatalogVO>();
					financeServicesInfo.setMessage(ConstantsFNP.FNP_SUCCESS);
					financeServicesInfo.setStepCode(" ");
				}
			}
			else if(isSubmitConfirm){
				if(catalogs==null || catalogs.size()==0 ){
					errors.reject("label.finserv.confirmcode");
				}
				//get default values
				else{
					List<FnpDefaultParamsVO> fnpDefaultParamsVOs =FnpGSDelegate.getDefaultParams();
					financeServicesInfo.setFnpDefaultParamsVOs(fnpDefaultParamsVOs);
					List<String> serviceIdList = new ArrayList<String>();
					for(FNPCatalogVO fnpCatalogVO :catalogs){
						serviceIdList.add(fnpCatalogVO.getId());
					}
					//get fnp parameters
					List<FNPParameterVO> paramList = FnpGSDelegate.retreiveAllFNPParameters(serviceIdList);
					fnpparameterList=paramList;
					if(paramList==null || paramList.size()==0){
						displayParameter = ConstantsFNP.FNP_EMPTY;
					}else{
						displayParameter = ConstantsFNP.FNP_YES;
					}
					financeServicesInfo.setFnpParams(paramList);
				}
			}else{
				catalogs=FnpGSDelegate.getFnpCatalogVOsByServiceCode(financeServicesInfo.getStepCode());
				/*List<FNPCatalogVO> tempCatalogs = catalogs;
				try{
					for(FNPCatalogVO fNPCatalogVO:tempCatalogs){
						if(fNPCatalogVO.getCode()==null || fNPCatalogVO.getId()==null ){
							catalogs.remove(fNPCatalogVO);
							System.out.println("kooi");
						}
					}
				}catch(Exception e){
					catalogs.remove(0);
				}*/
				catalogs.remove(0);
				displayParameter=ConstantsFNP.FNP_NO;
			}
		}
		financeServicesInfo.setSelectedCatalogs(catalogs);
		financeServicesInfo.setDisplayParam(displayParameter);
		return financeServicesInfo;
	}
	
	/**
	 * @param appId
	 * @param request
	 * @param model
	 * @return
	 */
	@ModelAttribute(Constants.__ADMIN_FINANCE_SERVICES_INFO_REQUEST_MODEL_KEY)
	public FinanceServicesInfo populateFinanceServicesInfoModel(
			@ModelAttribute(value = Constants.__ADMIN_FINANCE_SERVICES_INFO_REQUEST_MODEL_KEY) FinanceServicesInfo financeServicesInfo,
			HttpServletRequest request) {
		if(financeServicesInfo==null){
			 financeServicesInfo = new FinanceServicesInfo();
		}
		List<FNPCatalogVO> catalogList = FnpGSDelegate.retreiveFNPCatalog(null);
		financeServicesInfo.setFnpcatalogs(catalogList);
		return financeServicesInfo;
	}
	
	
}
